import 'package:flutter/material.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:flutter/foundation.dart' show kIsWeb;
import 'screens/login_screen.dart';
import 'screens/main_screen.dart';
import 'services/app_service.dart';
import 'dart:io';
import 'dart:convert';
import 'package:http/http.dart' as http;

// سېرۋېرنىڭ قوزغالغان-قوزغالمىغانلىقىنى تەكشۈرۈش
Future<bool> checkServerStatus() async {
  try {
    final response =
        await http.get(Uri.parse('http://localhost:8080/createUserInfoTable'));
    return response.statusCode == 200;
  } catch (e) {
    return false;
  }
}

// ئۇچۇر مۇلازىمەتچى توغرىسىدا تەكلىپ كۆرسىتىدىغان dialog
void showServerInfoDialog(BuildContext context) {
  showDialog(
    context: context,
    builder: (context) => AlertDialog(
      title: const Text('مۇلازىمەتچى ھەققىدە'),
      content: const Column(
        mainAxisSize: MainAxisSize.min,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text('مۇلازىمەتچى ئايرىم ئىجرا قىلىنىشى كېرەك:'),
          SizedBox(height: 12),
          Text('1. server/server.dart ھۆججىتىنى ئىجرا قىلىڭ'),
          Text('2. ئاندىن بۇ قوللانمىنى قايتا قوزغىتىڭ'),
        ],
      ),
      actions: [
        TextButton(
          onPressed: () => Navigator.pop(context),
          child: const Text('تامام'),
        ),
      ],
    ),
  );
}

void main() async {
  WidgetsFlutterBinding.ensureInitialized();

  // ساندان جەدۋىلى قۇرۇلۇشى
  try {
    final appService = AppService();
    final result = await appService.createUserInfoTable();
    debugPrint('ساندان جەدۋىلى قۇرۇش نەتىجىسى: $result');
  } catch (e) {
    debugPrint('ساندان جەدۋىلى قۇرۇش خاتالىقى: $e');
  }

  runApp(const TijaratApp());
}

class TijaratApp extends StatelessWidget {
  const TijaratApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'تىجارەت',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(
          seedColor: Colors.blue,
          primary: Colors.blue,
        ),
        useMaterial3: true,
        fontFamily: 'UKIJ CJK',
        inputDecorationTheme: InputDecorationTheme(
          filled: true,
          fillColor: Colors.grey.shade100,
          border: OutlineInputBorder(
            borderRadius: BorderRadius.circular(12),
            borderSide: BorderSide.none,
          ),
          enabledBorder: OutlineInputBorder(
            borderRadius: BorderRadius.circular(12),
            borderSide: BorderSide.none,
          ),
          focusedBorder: OutlineInputBorder(
            borderRadius: BorderRadius.circular(12),
            borderSide: const BorderSide(color: Colors.blue, width: 2),
          ),
          errorBorder: OutlineInputBorder(
            borderRadius: BorderRadius.circular(12),
            borderSide: const BorderSide(color: Colors.red, width: 2),
          ),
          focusedErrorBorder: OutlineInputBorder(
            borderRadius: BorderRadius.circular(12),
            borderSide: const BorderSide(color: Colors.red, width: 2),
          ),
        ),
        elevatedButtonTheme: ElevatedButtonThemeData(
          style: ElevatedButton.styleFrom(
            backgroundColor: Colors.blue,
            foregroundColor: Colors.white,
            elevation: 0,
            padding: const EdgeInsets.symmetric(vertical: 16),
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(12),
            ),
          ),
        ),
      ),
      locale: const Locale('en', 'US'),
      localizationsDelegates: const [
        GlobalMaterialLocalizations.delegate,
        GlobalWidgetsLocalizations.delegate,
        GlobalCupertinoLocalizations.delegate,
      ],
      supportedLocales: const [
        Locale('en', 'US'), // ئىنگلىزچە
      ],
      home: Builder(
        builder: (context) {
          // كىيىنكى فرەيمدا سېرۋېرنىڭ ھالىتىنى تەكشۈرۈش
          WidgetsBinding.instance.addPostFrameCallback((_) async {
            final isServerRunning = await checkServerStatus();
            if (!isServerRunning) {
              showServerInfoDialog(context);
            }
          });
          // MainScreen ئورنىغا LoginScreen كۆرسىتىمىز
          return const LoginScreen();
        },
      ),
    );
  }
}
